package com.cuanbo.dualscreenteachfu.utils;

import android.os.Handler;

import com.cuanbo.dualscreenteachfu.base.App;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.util.concurrent.TimeUnit;

/**
 * Web服务器
 */
public class WebServer {
    private static Server server;

    /**
     * 初始化
     */
    public static void init() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //注册AndServer
                server = AndServer.webServer(App.getInstance())
                        .port(8082)
                        .inetAddress(IpUtil.getIpAddress())
                        .listener(new Server.ServerListener() {
                            @Override
                            public void onStarted() {
                                LogUtil.add("状态", "已启动", "Web服务器");
                            }

                            @Override
                            public void onStopped() {
                                LogUtil.add("状态", "已停止", "Web服务器");
                            }

                            @Override
                            public void onException(Exception e) {
                                LogUtil.addError("Web服务器报错");
                                LogUtil.addError(e);
                            }
                        })
                        .timeout(10, TimeUnit.SECONDS)
                        .build();
                start();
            }
        }, 5000);
    }

    /**
     * 启动
     */
    public static void start() {
        if (!server.isRunning()) {
            server.startup();
        }
    }

    /**
     * 停止
     */
    public static void stop() {
        if (server.isRunning()) {
            server.shutdown();
        }
    }
}
